//
//  JKWebViewController.m
//  Baisi
//
//  Created by albert on 16/3/29.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKWebViewController.h"
#import "NJKWebViewProgress.h"

@interface JKWebViewController () <UIWebViewDelegate>
/** webView */
@property (weak, nonatomic) IBOutlet UIWebView *webView;
/** 后退按钮 */
@property (weak, nonatomic) IBOutlet UIBarButtonItem *goBackItem;
/** 前进按钮 */
@property (weak, nonatomic) IBOutlet UIBarButtonItem *goForwardItem;
/** 进度条 */
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toolBarBottomCons;
/** 进度代理对象 */
@property (nonatomic, strong) NJKWebViewProgress *progress;
@end

@implementation JKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.toolBarBottomCons.constant = JKCurrentHomeIndicatorHeight;
    [self.webView.scrollView jk_adapt_iOS_11_scrollView];
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(JKNavBarHeight, 0, 0, 0);
    self.webView.scrollView.scrollIndicatorInsets = self.webView.scrollView.contentInset;
    
    //先创建对象
    self.progress = [[NJKWebViewProgress alloc] init];
    
    //设置代理
    self.webView.delegate = self.progress;
    
    //block若引用
    __weak typeof(self) weakSelf = self;
    
    //设置进度
    self.progress.progressBlock = ^(float progress){
        JKLog(@"%f", progress);
        weakSelf.progressView.progress = progress;
        weakSelf.progressView.hidden = (progress == 1.0);
    };
    
    //还想自己代理的话，这样写，框架拿走了代理，又提供了一个代理，绕了一圈
    self.progress.webViewProxyDelegate = self;
    
    //加载传进来的url
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    });
}

//后退
- (IBAction)goBack:(id)sender {
    [self.webView goBack];
}

//前进
- (IBAction)goForward:(id)sender {
    [self.webView goForward];
}

//刷新
- (IBAction)reload:(id)sender {
    [self.webView reload];
}

#pragma mark - <UIWebViewDelegate>
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //控制后退和前进是否可点击
    self.goBackItem.enabled = webView.canGoBack;
    self.goForwardItem.enabled = webView.canGoForward;
    JKLog(@"webViewDidFinishLoad");
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    JKLog(@"didFailLoadWithError");
}

- (void)dealloc{
    JKLog(@"dealloc");
}
@end
